<template>
  <el-dialog :title="title" :visible.sync="visible" width="55%" sytle="height:600px">
      <el-form
        :model="form"
        ref="form"
        label-width="100px"
      >
        <el-form-item label="蛋糕组成" required v-show="type === 'add'">
          <searchGoodsInput @select="handleGoodsSelect"></searchGoodsInput>

          <div>
            <div class="goods-item" v-for="(item,index) in goodsList" :key="index">
              <span class="item-index">{{ index + 1 }}</span>
              <div class="left">
                <div class="item-row">
                  <label for="">名称 / 规格</label>
                  <el-input
                    class="c-409eff"
                    placeholder="名称 / 规格"
                    readonly
                    v-model="item.skuName"
                    size="small"
                  ></el-input>
                </div>
                <div class="item-row">
                  <label class="required">链接名称</label>
                  <el-input
                    type="textarea"
                    autosize
                    v-model.trim="item.linkName"
                    placeholder="链接名称"
                    maxlength="50"
                    show-word-limit
                    size="medium"
                  ></el-input>
                </div>
                <div class="item-row">
                  <label class="required">营销名称</label>
                  <el-input
                    type="textarea"
                    autosize
                    v-model.trim="item.marketName"
                    placeholder="营销名称"
                    maxlength="50"
                    show-word-limit
                  ></el-input>
                </div>
              </div>
              <div class="right">
                <el-upload
                  list-type="picture-card"
                  :data="{tag:'groupbuy'}"
                  action="/api/xmbz-goods/file/upload"
                  :show-file-list="false"
                  :on-success="(res,file)=>{return handleAvatarSuccess(res,file, item)}"
                >
                  <img v-if="item.imageUrl&&item.imageUrl.length" :src="item.imageUrl" class="avatar" />
                  <i v-else class="el-icon-plus"></i>
                </el-upload>
              </div>

              <i class="el-icon-error del-icon" @click="handleDelGoods(index)"></i>
            </div>
          </div>
        </el-form-item>
        <el-form-item label="已选商品" required v-if="type === 'edit'">
          <div :title="item.linkName" class="edit-goods-item" v-for="(item, index) in editGoodsList" :key="index">
            <img class="edit-goods-item-image" :src="item.linkHeadPicture" />
            <div class="edit-goods-item-name ellipsis">{{ item.linkName }}</div>
          </div>
        </el-form-item>
        
        <el-form-item label="城市">
          <el-checkbox class="lh-24" :indeterminate="form.isIndeterminate" v-model="form.checkAll" @change="handleCheckAllCityChange()">全选</el-checkbox>
          <el-checkbox-group class="lh-24" v-model="form.cityIds">
            <el-checkbox v-for="city in cityList" :label="city.value" :key="city.value" @change="handleCheckCityChange()">{{city.label}}</el-checkbox>
          </el-checkbox-group>
        </el-form-item>

        <el-form-item label="链接有效期" required>
          <el-date-picker
            v-model="form.startTime"
            type="datetime"
            placeholder="开始时间"
            size="small"
            class="w-200 mr-10"
            value-format="yyyy-MM-dd HH:mm:ss"
            default-time="00:00:00"
          ></el-date-picker>
          <el-date-picker
            v-model="form.endTime"
            type="datetime"
            size="small"
            placeholder="结束时间"
            class="w-200"
            value-format="yyyy-MM-dd HH:mm:ss"
            default-time="23:59:59"
          ></el-date-picker>
        </el-form-item>
      </el-form>

    <span slot="footer" class="dialog-footer">
      <el-button @click="visible = false">取 消</el-button>
      <el-button type="primary" @click="confirm">确 定</el-button>
    </span>
  </el-dialog>
</template>

<script>
import {
  citySelect,
  batchGroupSave,
  batchGroupUpdate,
  getgroupDetails,
} from "@/api/commodityfiles";
import searchGoodsInput from "./searchGoodsInput";

export default {
  components: {
    searchGoodsInput,
  },
  data() {
    return {
      visible: false,
      type: 'add', // add，edit
      cityList: [],
      form: {
        checkAll: false,
        indeterminate: false,
        cityIds: [],
        startTime: '',
        endTime: '',
      },
      goodsList: [],
      editGoodsList: [],
    };
  },
  methods: {
    show({ type, editGoodsList } = {}) {
      this.visible = true;
      this.type = type;
      this.init();
      if (type === 'edit') {
        this.editGoodsList = editGoodsList;
        this.setGroupDetail(editGoodsList[0].id)
      }
    },
    init() {
      this.form = {
        checkAll: false,
        indeterminate: false,
        cityIds: [],
        startTime: '',
        endTime: '',
      }
      this.goodsList = []
    },
    confirm() {
      const validMsg = this.validate()
      if (validMsg) {
        this.$message({
          message: validMsg,
          type: "warning",
        });
        return
      }
      const requestMap = {
        'add': batchGroupSave,
        'edit': batchGroupUpdate,
      }
      requestMap[this.type](this.getParams()).then(res => {
        this.$notify({
          title: "提示",
          message: "添加商品成功",
          type: "success",
          duration: 4000,
        });
        this.$emit('confirm');
        this.visible = false;
      })
    },
    getParams() {
      const params = {
        linkType: 1,
        startTime: this.form.startTime,
        endTime: this.form.endTime,
        cityIds: this.form.cityIds.join(','),
        list: this.type === 'add' ? this.goodsList.map(item => {
          return {
            skuId: item.skuId,
            linkName: item.linkName,
            marketName: item.marketName,
            imgUrl: item.imageUrl,
          }
        }) : undefined,
        ids: this.type === 'edit' ? this.editGoodsList.map(item => item.id) : undefined,
      }
      return params;
    },
    validate() {
      if (this.type === 'add' && (!this.goodsList || !this.goodsList.length)) {
        return '蛋糕组成不能为空！'
      }

      if (this.type === 'add' && this.goodsList && this.goodsList.length) {
        if (this.goodsList.some(item => !item.linkName)) {
          return '链接名称不能为空！'
        }
        if (this.goodsList.some(item => !item.marketName)) {
          return '营销名称不能为空！'
        }
        if (this.goodsList.some(item => !item.imageUrl)) {
          return '图片称不能为空！'
        }
      }

      if (!this.form.startTime || !this.form.endTime) {
        return '链接有效期不能为空！'
      }
    },
    handleCheckAllCityChange() {
      this.form.cityIds = this.form.checkAll ? this.cityList.map(item => item.value) : []
      this.form.isIndeterminate = false
    },
    handleCheckCityChange(item) {
      const checkedCount = this.form.cityIds.length
      this.form.checkAll = checkedCount === this.cityList.length;
      this.form.isIndeterminate = checkedCount > 0 && checkedCount < this.cityList.length;
    },
    getCityList() {
      citySelect().then(res=>{
        this.cityList = res.data.data
        this.cityList.map((item,index)=>{
          item.label = item.deptName
          item.value = item.id + ''
        })
      })
    },
    // 单个主图开始上传
    handleAvatarSuccess(response, file, item) {
      item.imageUrl = response.data;
    },
    handleSelectGoods() {
      this.$refs.selectGoodsDialog.show()
    },
    handleDelGoods(i) {
      this.goodsList.splice(i, 1)
    },
    handleGoodsSelect(item) {
      if (this.goodsList.some(g => g.skuId === item.skuId)) {
        this.$message({
          type: 'warning',
          message: '该规格已存在，请勿重复添加'
        })
        return
      }
      this.goodsList.push({
        ...item,
        skuName: item.goodsName + ' / ' + item.specs,
        linkName: item.goodsName + item.specs,
        marketName: item.goodsName + item.specs,
        imageUrl: ''
      })
    },
    setGroupDetail(groupId) {
      getgroupDetails({id: groupId}).then(res => {
        const data = res.data.data
        const detail = res.data.data.list ? res.data.data.list[0] : {}
        const cityIds = detail.cityIds ? detail.cityIds.split(',') : []
        const checkAll = this.cityList.every(item => cityIds.includes(item.value))
        const checkSome = this.cityList.some(item => cityIds.includes(item.value)) && !this.cityList.every(item => cityIds.includes(item.value))
        this.form.startTime = data.startTime;
        this.form.endTime = data.endTime;
        this.form.cityIds = cityIds;
        this.form.isIndeterminate = checkSome;
        this.form.checkAll = checkAll;
      })
    }
  },
  computed: {
    title() {
      const titleMap = {
        'add': '批量新增单品',
        'edit': '批量修改单品',
      }
      return titleMap[this.type]
    }
  },
  created() {
    this.getCityList();
  }
};
</script>
<style lang="scss" scoped>
.goods-item {
  border: 1px dashed #d3d3d3;
  border-radius: 10px;
  padding: 10px 22px;
  position: relative;
  margin-top: 20px;
  .left {
    display: inline-block;
    width: 70%;
  }
  .right {
    display: inline-block;
    vertical-align: top;
    margin-left: 28px;
    ::v-deep .el-upload--picture-card {
      width: 100px !important;
      height: 100px !important;
      line-height: 100px !important;
    }
    .avatar {
      width: 100%;
      height: 100%;
      display: block;
    }
  }
  .item-row {
    display: flex;
    line-height: 40px;
    margin-bottom: 10px;
    label {
      width: 120px;
      &.required {
        &::before {
          content: '*';
          color: #F56C6C;
          margin-right: 4px;
        }
      }
    }
    .skucodes {
      padding: 8px;
      border-radius: 4px;
      border: 1px solid #108ee9;
      color: #108ee9;
      flex: 1;
    }
    ::v-deep .el-textarea .el-input__count {
      bottom: 10px;
    }
  }
  .item-index {
    position: absolute;
    top: -20px;
    left: 20px;
    background: #fff;
    font-size: 20px;
    font-weight: bold;
  }
  .del-icon {
    position: absolute;
    top: -15px;
    right: -15px;
    font-size: 34px;
  }
}
.edit-goods-item {
  border: 1px dashed #d3d3d3;
  border-radius: 6px;
  padding: 5px;
  display: inline-block;
  margin: 0 10px 10px 0;
  text-align: center;
  width: 110px;
  .edit-goods-item-image {
    width: 100px;
    height: 100px;
    border-radius: 6px;
  }
  .edit-goods-item-name {
    font-weight: bold;
    line-height: 18px;
    font-size: 14px;
  }
}
</style>